package com.yuge.xiaohua.adapter

import android.content.Context
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import com.squareup.picasso.Picasso
import com.yuge.xiaohua.R
import com.yuge.xiaohua.model.JokeInfoEntry

/**
 * Created by Mrper on 15-12-14.
 */
class JokeAdapter(ctx: Context?, jokes: Collection<JokeInfoEntry>?) : BaseAdapter(){

    private var ctx: Context? = null
    private var jokes : Collection<JokeInfoEntry>? = null

    init{
        this.ctx = ctx;
        this.jokes = jokes;
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
        var item : JokeInfoEntry? = this.jokes!!.elementAt(position);
        var holder : ViewHolder? = null
        var convertView = convertView
        if(convertView == null){
            holder = ViewHolder()
            convertView = View.inflate(ctx, R.layout.listitem_joke,null)
            holder.txtJoke = convertView.findViewById(R.id.txtJoke) as TextView
            holder.imgJoke = convertView.findViewById(R.id.imgJoke) as ImageView
            convertView.tag = holder
        }else{
            holder = convertView.tag as ViewHolder
        }
        holder.txtJoke!!.text = item!!.content
        if(!TextUtils.isEmpty(item.picUrl))
            Picasso.with(ctx).load(item.picUrl).into(holder.imgJoke)
        else
            holder.imgJoke!!.setImageBitmap(null)
        return convertView;
    }

    override fun getItem(position: Int): Any? {
        return jokes!!.elementAt(position)
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getCount(): Int {
        return this.jokes!!.size
    }

    data class  ViewHolder(var txtJoke: TextView?=null,var imgJoke: ImageView?=null)

}